package com.media.controller;

import com.media.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Servlet 注解配置信息
 */
@WebServlet(name = "LoginServlet",value = "/login")
public class LoginController extends HttpServlet {
    /**
     * post请求 会执行doPost方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
}
     /**
      * get请求 会执行doGet方法
      * @param request
      * @param response
      * @throws ServletException
      * @throws IOException
      */
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


         System.out.println("servlet 请求");

         request.setCharacterEncoding("utf-8");

         String username = request.getParameter("username");
         String password = request.getParameter("password");

         HttpSession session = request.getSession();

         if("1".equals(request.getParameter("invalidate")) && session.getAttribute("username") != null){
             session.invalidate();
             //session.removeAttribute("username");
             response.sendRedirect("login.jsp");
         }

         try {

             Connection connection = DBUtil.getConnection();

             //sql 模板
             String sql = "select * from user where username = ? and password = ?";
             //使用PreparedStatement对象执行sql语句
             PreparedStatement ps = connection.prepareStatement(sql);

             ps.setString(1,username);
             ps.setString(2,password);

             ResultSet rs = ps.executeQuery();

             //response.setContentType("text/html;charset=UTF-8");

             PrintWriter out = response.getWriter();

             if(rs.next()){
                 //表示登录成功
                 session.setAttribute("username",username);
                 response.sendRedirect("home.jsp");
             }else{
                 //表示登录未成功
                 out.print("登录失败,3秒之后跳转登录页面...");
                 response.setHeader("refresh","3;url=login.jsp");
             }

             //服务端跳转
             //request.getRequestDispatcher("home.jsp").forward(request,response);

             DBUtil.close(connection,ps,rs);

         }catch (Exception e){
             e.printStackTrace();
         }
     }
}


